package com.nsgf.library.ui.page;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.MainNsgfActivity;
import com.nsgf.library.MainNsgfRegionActivity;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.User;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.databinding.DialogLoginTypeDataBinding;
import com.nsgf.library.databinding.FragmentLoginBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.utils.BaseAlterDialog;
import com.nsgf.library.utils.SPUtil;
import com.nsgf.library.utils.ToastUtils;

import cn.jiguang.api.utils.JCollectionAuth;
import cn.jpush.android.api.JPushInterface;

public class LoginActivity extends BaseActivity {
    private LoginStates mStates;

    private LoginDialogStates mDialogStates;
    private FragmentLoginBinding mBinding;
    private AccountRequester mAccountRequester;
    DialogLoginTypeDataBinding binding;
    private Dialog dialog;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(LoginStates.class);
        mDialogStates = getActivityScopeViewModel(LoginDialogStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);

    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.fragment_login, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (FragmentLoginBinding) getBinding();

        getLifecycle().addObserver(mAccountRequester);

        mBinding.toggleButtonShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 切换为可见密码
                    mBinding.etLoginPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    // 切换为不可见密码
                    mBinding.etLoginPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }

                // 设置光标位置到末尾
                mBinding.etLoginPass.setSelection(mBinding.etLoginPass.getText().length());
            }
        });
        mAccountRequester.getUserResult().observe(this, userInfoDataResult -> {

            getController().dismissLoading();
            if (userInfoDataResult.getResponseStatus().isSuccess()) {

                if (!userInfoDataResult.getResult().getData().getAdmin().isSingleProject()) {

                    dialog = new Dialog(LoginActivity.this, R.style.dialogstyle);
                    View view = View.inflate(LoginActivity.this, R.layout.dialog_login_user_type, null);

                    binding = DataBindingUtil.bind(view);
                    binding.setClickDialog(new DialogClickProxy());
                    binding.ivUserTypeMore.setAlpha(0.6f);
                    binding.tvUserTypeMore.setAlpha(0.6f);
                    dialog.setContentView(view);
                    Window window = dialog.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams lp = window.getAttributes();
                    lp.width = getResources().getDisplayMetrics().widthPixels;
                    window.setAttributes(lp);
                    window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
                    dialog.show();

                } else {
                    startActivity(new Intent().setClass(LoginActivity.this, MainNsgfActivity.class));
                    finish();
                }
            } else
                Error(userInfoDataResult.getResponseStatus().getE());
        });
        mAccountRequester.getUserDataResult().observe(this, dataResult -> {

            if (200 == dataResult.getResponseCode()) {
                UserInfo.getInstance().setTokenValue(dataResult.getData().getTokenInfo().getTokenValue());
                UserInfo.getInstance().setTokenName(dataResult.getData().getTokenInfo().getTokenName());
                UserInfo.getInstance().setName(dataResult.getData().getUser().getUsername());
                UserInfo.getInstance().setId(String.valueOf(dataResult.getData().getUser().getId()));

//                JPushInterface.setAlias(LoginActivity.this, dataResult.getData().getUser().getId(), "test_" + dataResult.getData().getUser().getId());

                JPushInterface.setAlias(LoginActivity.this, dataResult.getData().getUser().getId(), String.valueOf(dataResult.getData().getUser().getId()));

                UserInfo.getInstance().setPhone(dataResult.getData().getUser().getPhone());
                UserInfo.getInstance().setDeptName(dataResult.getData().getUser().getDeptName());

                mAccountRequester.setTokenResult();
            } else {
                getController().dismissLoading();
                new BaseAlterDialog(this, R.style.dialogstyle,
                        dataResult.getMsg(), "确定", "登录失败",
                        (dialog, confirm) -> {
                            dialog.dismiss();

                        }).show();
            }
        });
        mStates.name.set(SPUtil.get("userName", "", LoginActivity.this));
        mStates.password.set(SPUtil.get("userPassword", "", LoginActivity.this));
    }

    public static class LoginStates extends StateHolder {

        public final State<String> name = new State<>("");//app

        public final State<String> password = new State<>("");//nsgf@dev2024

        public final State<Boolean> loadingVisible = new State<>(false);

    }

    public static class LoginDialogStates extends StateHolder {

        public final State<String> name = new State<>("");

    }


    public class ClickProxy {

        public void login() {

            //TODO tip 5：通过双向绑定，使能通过 state-ViewModel 中与 xml 控件发生绑定的"可观察数据" 拿到控件数据，
            // 避免直接接触控件实例而埋下 Null 安全一致性隐患。

            if (TextUtils.isEmpty(mStates.name.get()) || TextUtils.isEmpty(mStates.password.get())) {

                new BaseAlterDialog(LoginActivity.this, R.style.dialogstyle,
                        getString(R.string.username_or_pwd_incomplete), "确定", "登录失败",
                        (dialog, confirm) -> {
                            dialog.dismiss();

                        }).show();
                return;
            }

            getController().displayLoading();

            User user = new User(mStates.name.get(), mStates.password.get());
            if (mBinding.checkbox.isChecked()) {
                SPUtil.put("userName", user.getName(), LoginActivity.this);
                SPUtil.put("userPassword", user.getPassword(), LoginActivity.this);
            } else {
                SPUtil.remove("userName", LoginActivity.this);
                SPUtil.remove("userPassword", LoginActivity.this);
            }
            mAccountRequester.requestLogin(user);
            mStates.loadingVisible.set(true);

        }

        public void codeLogin() {
            loginStatus(false);
        }

        public void passLogin() {
            loginStatus(true);
        }

        public void sendCode() {
            if (TextUtils.isEmpty(mStates.name.get())) {
                ToastUtils.showLongToast(getString(R.string.username_or_pwd_incomplete));
                return;
            }
            timer.start();
        }
    }


    public class DialogClickProxy {
        public void cancel() {
            dialog.dismiss();
        }

        public void clickSing() {
            binding.ivUserTypeSing.setAlpha(1f);
            binding.tvUserTypeSing.setAlpha(1f);
            binding.ivUserTypeMore.setAlpha(0.6f);
            binding.tvUserTypeMore.setAlpha(0.6f);
        }

        public void clickMore() {
            binding.ivUserTypeSing.setAlpha(0.6f);
            binding.tvUserTypeSing.setAlpha(0.6f);
            binding.ivUserTypeMore.setAlpha(1f);
            binding.tvUserTypeMore.setAlpha(1f);
        }

        public void confirm() {
            if (1f == binding.ivUserTypeSing.getAlpha()) {
                startActivity(new Intent().setClass(LoginActivity.this, MainNsgfActivity.class));
                UserInfo.getInstance().setActivityType("mainActivity");
            } else {

                UserInfo.getInstance().setProjectCode("");
                UserInfo.getInstance().setProjectName("");
                startActivity(new Intent().setClass(LoginActivity.this, MainNsgfRegionActivity.class));
                UserInfo.getInstance().setActivityType("mainRegionActivity");
            }
            dialog.dismiss();
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    /**
     * 是否账号密码登录
     *
     * @param status
     */
    private void loginStatus(boolean status) {

        if (status) {
            mBinding.etLoginPass.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
            mBinding.etLoginPass.setHint("请输入密码");
        } else {
            mBinding.etLoginPass.setInputType(InputType.TYPE_CLASS_NUMBER);
            mBinding.etLoginPass.setHint("请输入验证码");
        }
        mBinding.tvSendLoginCode.setVisibility(!status ? View.VISIBLE : View.GONE);
        mBinding.llLoginSavePass.setVisibility(status ? View.VISIBLE : View.INVISIBLE);
        mBinding.tvLoginCode.setVisibility(status ? View.VISIBLE : View.GONE);
        mBinding.tvLoginPass.setVisibility(!status ? View.VISIBLE : View.GONE);
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mBinding.tvSendLoginCode.setText(millisUntilFinished / 1000 + "秒");
            mBinding.tvSendLoginCode.setTextColor(Color.parseColor("#999999"));
        }

        @Override
        public void onFinish() {
            mBinding.etLoginPass.requestFocus();
            mBinding.tvSendLoginCode.setText("重新获取");
            mBinding.tvSendLoginCode.setClickable(true);
            mBinding.tvSendLoginCode.setTextColor(Color.parseColor("#165dff"));
        }
    };
}
